<template>
  <ul class="list">
    <li
      class="item"
      v-for="item of letters"
      :key="item"
      @click="handleLetterClick"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      :ref="item"
    >
      {{ item }}
    </li>
  </ul>
</template>

<script>
export default {
  name: "CityAlphabet",
  props: {
    cities: Object,
  },
  // 设置计算属性letters为this.cities中所有键名组成的数组
  computed: {
    letters() {
      const letters = [];
      for (let k in this.cities) {
        letters.push(k);
      }
      return letters;
    },
  },
  data() {
    return {
      touchStatus: false,
      startY: 0,
      timer: null,
    };
  },
  // 当页面重新渲染并更新后将this.startY设置为CityAlphabet组件中A的DOM离外层组件的高度
  updated() {
    this.startY = this.$refs.A[0].offsetTop;
  },
  methods: {
    // 当item组件被点击的时候触发父组件的“change”事件
    handleLetterClick(e) {
      this.$emit("change", e.target.innerText);
    },
    // 当item组件开始被触摸时将this.touchStatus设置为true
    handleTouchStart() {
      this.touchStatus = true;
    },
    // 当item组件在触摸移动时并且touchStatus为true时，设置touchY为当前“字母”离List组件顶部的距离；
    // 设置index为当前“字母”在letters中的下标；
    // 如果index在letters.length范围内就触发父组件的“change”事件
    handleTouchMove(e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer);
        // return
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 158;
          const index = Math.floor((touchY - this.startY) / 40);
          if (index >= 0 && index < this.letters.length) {
            this.$emit("change", this.letters[index]);
          }
          this.timer=null;
        }, 16);
      }
    },
    // 当触摸事件结束时将touchStatus设置为false
    handleTouchEnd() {
      this.touchStatus = false;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/assets/style/varibles.scss";
.list {
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: absolute;
  top: 1.58rem;
  right: 0;
  bottom: 0;
  width: 0.4rem;
  .item {
    line-height: 0.4rem;
    text-align: center;
    color: $bgColor;
  }
}
</style>